import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/enum_entity.dart';
import 'package:library_base/entities/print_detail_entity.dart';
import 'package:library_base/ext/list_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/route/routers.dart';
import 'package:library_base/utils/channel.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:library_base/base/base_list_state.dart';
import 'package:module_wms/page/outbound_orders/as_order/order_detail/print_detail/print_detail_controller.dart';
import 'package:module_wms/page/outbound_orders/as_order/order_detail/print_detail/print_detail_page_ui.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

class PrintDetailPage extends StatefulWidget {
  const PrintDetailPage({Key? key}) : super(key: key);

  @override
  _PrintDetailPageState createState() => _PrintDetailPageState();
}

class _PrintDetailPageState
    extends BaseListState<PrintDetailEntity, PrintDetailEntity, PrintDetailPage, PrintDetailController> {

  MethodChannel fromAndroidChannel = const MethodChannel("connectStatus");

  MethodChannel flutterUiUpdateChannel = const MethodChannel("flutterUiUpdateChannel");

  @override
  ScrollController get scrollController => AutoScrollController();

  @override
  PrintDetailController registerController() => Get.find<PrintDetailController>();

  @override
  void onCreate() {
    super.onCreate();
    setTitle(MultiLanguage.printSalesOrder.tr);
    setNavigationBarColor(ThemeUtil.getTheme().colorScheme.secondary);
    fromAndroidChannel.setMethodCallHandler(flutterMethod);
    flutterUiUpdateChannel.setMethodCallHandler(flutterMethod);
    sendAndroidChannel.invokeMethod("registerListener", "AsOrderPage");
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async{
    logger.i("flutterMethod = ${methodCall.method}");
    switch (methodCall.method) {
      case 'onConnect':
        baseGetxController!.isConnected.value = true;
        if (mounted) {
          setState(() {});
        }
        break;

      case 'onDisconnect':
        baseGetxController!.isConnected.value = false;
        if (mounted) {
          setState(() {});
        }
        break;

      case 'DISMISS':
        Get.back();
        break;

      case 'SLIDING_INDEX':
        (scrollController as AutoScrollController).scrollToIndex(int.parse(methodCall.arguments as String));
        break;
    }
  }

  @override
  void controllerOnCreate() {
    useRefresh = true;
    isCanRefresh = false;
    isCanLoad = false;
    enableControlFinishLoad = false;
    enableControlFinishRefresh = true;
    baseGetxController?.easyRefreshController = controller;
  }

  @override
  Widget? getMainWidget(BuildContext context) {
    return MultiStateWidget(
      emptyWidget: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            LocalImage('admin_empty', package: Constant.packAdmin(), width: 0.6.sw),
            Text(MultiLanguage.noSuchProduct.tr, style: TextStyles.textSecondary28),
            SizedBox(height: 80.h),
            Row(mainAxisAlignment: MainAxisAlignment.center, children: [
              GradientButton(
                ThemeUtil.getTheme(),
                width: 0.4.sw,
                height: 80.w,
                text: MultiLanguage.reload.tr,
                onPressed: baseGetxController!.tryReLoad,
              ),
            ])
          ]),
      controller: baseGetxController!.multiControllerOut,
      child: Stack(
        children: [
          Column(
            children: [
              gapH18,
              Expanded(
                child: Container(
                    color: ThemeUtil.getTheme().secondaryBgColor(),
                    child: getListView(context, baseGetxController)),
              ),
              // Container(
              //   decoration: rectTop,
              //   width: double.infinity,
              //   height: 166.w,
              //   // decoration: rectTop,
              //   child: Stack(
              //     children: [
              //       Positioned(
              //         top: (166.w - 100.w) / 2,
              //         left: 24.w,
              //         child: GradientButton(ThemeUtil.getTheme(),
              //             width: 700.w,
              //             padding: edgeAll24 as EdgeInsets,
              //             text: Messages.printAll.tr,
              //             onPressed: () {
              //               baseGetxController!.onPrintAll();
              //             }),
              //       )
              //     ],
              //   ),
              // ),
            ],
          ),
          Positioned(
              top: 50.w,
              right: 30.w,
              child: GestureDetector(
                onTap: () {
                  if (baseGetxController!.isConnected.value) {
                    Get.toNamed(Routers.DEVICE_DETAIL_PAGE);
                  } else {
                    Get.toNamed(Routers.SEARCH_DEVICE_PAGE);
                  }
                },
                child: GetBuilder<PrintDetailController>(builder: (logic) {
                  return Opacity(
                    opacity: 0.9,
                    child: Container(
                      alignment: Alignment.center,
                      padding: edgeAll8,
                      decoration: BoxDecoration(
                          color: baseGetxController!.isConnected.value
                              ? ThemeUtil.getTheme().bluetoothColor()
                              : ThemeUtil.getTheme().noBluetoothColor(),
                          borderRadius:
                              const BorderRadius.all(Radius.circular(20.0))),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          LocalImage(
                              baseGetxController!.isConnected.value
                                  ? 'common_bluetooth_connected'
                                  : 'common_bluetooth_no_connected',
                              package: Constant.packLib(),
                              width: 40.w,
                              height: 40.w),
                          gapW8,
                          Text(
                            baseGetxController!.isConnected.value
                                ? MultiLanguage.connected.tr
                                : MultiLanguage.no_connection.tr,
                            style: secondaryTextColor26,
                            textAlign: TextAlign.center,
                          )
                        ],
                      ),
                    ),
                  );
                }),
              ))
        ],
      ),
    );
  }

  @override
  List<Widget> buildListItem(BuildContext context) {
    baseGetxController!.globalKeys.clear();
    return baseGetxController!.listData.value.buildItem((index, element) {
      baseGetxController!.globalKeys.add(GlobalKey(debugLabel:element.orderNumber));
      return buildItem(element,index,baseGetxController!.globalKeys[index],onPrintSingle:baseGetxController!.onPrintSingle);
    }, dividingLine: () {
      return gapH18;
    }, divideType: DivideType.MIDDLE_WITH_BOTTOM);
  }

  @override
  void onDestroy() {
    super.onDestroy();
    sendAndroidChannel.invokeMethod("unbindListener","AsOrderPage");
  }
}
